package com.firstsight.micro.homedo.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 阿里云文件操作
 */
public class AliyunOssUtil {

  static final String ENDPOINT = "oss-cn-shanghai.aliyuncs.com";
  static final String ACCESS_KEY_ID = "LTAIB2o3dQHye9Bv";
  static final String ACCESS_KEY_SECRET = "Z5INSj7mQ6ZHEsZlRbfoMzp5CExj9E";
  static final String BUCKET_NAME = "wuyou-resource";
  static final String SUFFIX_REG = "aliyuncs.com/";
  static final String URL_PREFIX_HTTP = "http://";
  static final String URL_PREFIX_HTTPS = "https://";

  static OSSClient ossClient = null;

  static OSSClient getClient() {
    if (null == ossClient) {
      ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }
    return ossClient;
  }

  /**
   * 获取阿里云服务器上的文件访问前缀
   *
   * @return
   */
  public static String getObjectUrlPrefix() {
    return BUCKET_NAME + "." + ENDPOINT + "/";
  }

  /**
   * 上传文件
   *
   * @param key
   * @param filename
   * @throws OSSException
   * @throws ClientException
   * @throws FileNotFoundException
   */
  public static String uploadFile(String key, String filename)
          throws OSSException, ClientException, FileNotFoundException {
    File file = new File(filename);
    return uploadFile(key, file);
  }

  /**
   * 上传文件
   *
   * @param key
   * @param file
   * @return
   * @throws FileNotFoundException
   */
  public static String uploadFile(String key, File file){
    getClient().putObject(BUCKET_NAME, key, file);
    return urlProtocol(getObjectUrlPrefix() + key) ;
  }

  /**
   * 上传文件
   *
   * @param key
   * @param is
   * @return
   * @throws FileNotFoundException
   */
  public static String uploadFile(String key, InputStream is){
    getClient().putObject(BUCKET_NAME, key, is);
    return  urlProtocol(getObjectUrlPrefix() + key) ;
  }

  /**
   * 下载文件
   *
   * @param key
   * @param filename
   * @throws OSSException
   * @throws ClientException
   */
  public static void downloadFile(String key, String filename)
          throws OSSException, ClientException {
    getClient().getObject(new GetObjectRequest(BUCKET_NAME, key), new File(filename));
  }


  /**
   * 删除一个OSS文件对象
   *
   * @param key
   */
  public static void deleteObject(String key) {
    getClient().deleteObject(BUCKET_NAME, key);
  }

  public static void deleteObjectByUrl(String url) {
    if (StringUtils.isEmpty(url)) {
      return;
    }
    String[] aliyuns = url.split(SUFFIX_REG);
    deleteObject(aliyuns[aliyuns.length - 1]);
  }

  public static boolean existObject(String key) {
    return getClient().doesObjectExist(BUCKET_NAME, key);
  }

  public static boolean existObjectByUrl(String url) {

    if (StringUtils.isEmpty(url)) {
      return false;
    }
    String[] aliyuns = url.split(SUFFIX_REG);
    return existObject(aliyuns[aliyuns.length - 1]);
  }

  public static String urlProtocol(String url) {
    if (url.startsWith(URL_PREFIX_HTTP) || url.startsWith(URL_PREFIX_HTTPS)) {
      return url;
    }
    return URL_PREFIX_HTTPS + url;
  }
//  public static String urlEncode(String urls){
//    String str = "";
//    List<String> urlList = Collections.singletonList(urls);
//    if (urls.contains(",")) {
//      urlList = Arrays.asList(urls.split(","));
//    } else if (urls.contains("||")) {
//      urlList = Arrays.asList(urls.split("\\|\\|"));
//    }else if(StringUtil.isBlank(urls)){
//      throw new BizException(BizErrorCodeEnum.NULL_ERROR);
//    }
//    for (String url : urlList) {
//      url = com.homedo.microservice.ind.linker.basicservice.util.AliyunOssUtil.urlProtocol(url);
//      str = str+url+"||";
//    }
//    int begin1 = str.lastIndexOf("||");
//    str = str.substring(0,begin1);
//    return str;
//  }
  public static void main(String[] args){
    File file = new File("C:\\Users\\yanshuchun\\Desktop\\sssss.jpg");
    try {
      String s = uploadFile("sssss.jpg", file);
      System.out.println(s);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
//    try (FileOutputStream bos = new FileOutputStream("F:\\chrome下载\\测试.zip");
//         ZipOutputStream zos = new ZipOutputStream(bos)) {
//      String a = "//hemodo-project.oss-cn-beijing.aliyuncs.com/0bdd1e24-d3dc-4de9-b78e-0ff96fd8e47d_0151.酒店客房智能控制解决方案.pdf||//hemodo-project.oss-cn-beijing.aliyuncs.com/02b7953e-9e19-4874-b881-1b4cb6732e98_0151.酒店客房智能控制解决方案.doc";
//      System.out.println(urlEncode(a));
//      List<String> urls = Lists.newArrayList();
//      urls.add(
//              "//hemodo-project.oss-cn-beijing.aliyuncs.com/0bdd1e24-d3dc-4de9-b78e-0ff96fd8e47d_0151.酒店客房智能控制解决方案.pdf");
//      urls.add(
//              "//hemodo-project.oss-cn-beijing.aliyuncs.com/02b7953e-9e19-4874-b881-1b4cb6732e98_0151.酒店客房智能控制解决方案.doc");
//      for (String url : urls) {
//        url = AliyunOssUtil.urlProtocol(url);
//        int begin = url.lastIndexOf("/");
//        url = URLDecoder.decode(url, "UTF-8");
//        String encode = URLEncoder.encode(url.substring(begin + 1), "UTF-8");
//        String str = url.substring(0, begin + 1) + encode;
//        URL remoteUrl = new URL(str);
//
//        String entryFileName = url.substring(begin + 1);
//        zos.putNextEntry(new ZipEntry(URLEncoder.encode(entryFileName, "UTF-8")));
//
//        URLConnection urlConnection = remoteUrl.openConnection();
//        InputStream is = urlConnection.getInputStream();
//        byte[] buffer = new byte[1024];
//        int r = 0;
//        while ((r = is.read(buffer)) != -1) {
//          zos.write(buffer, 0, r);
//        }
//        is.close();
//      }
//
//      zos.flush();
//      zos.close();
//
//      FileInputStream is = new FileInputStream("F:\\chrome下载\\测试.zip");
//
//      StringBuilder fileName = new StringBuilder();
//      fileName.append(UUID.randomUUID().toString()).append("_").append("压缩包").append(".zip");
//
//      AliyunOssUtil.uploadFile(fileName.toString(), is);
//
//      String zipUrl = AliyunOssUtil.getObjectUrlPrefix() + fileName;
//
//      System.out.println("zipUrl");
//
//      System.out.println(zipUrl);
//
//      is.close();
//    } catch (Exception ex) {
//      ex.printStackTrace();
//    }
//  }
}
